<template>
   <div class=''>
       <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data="rolesList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',index===0?'bdtop':'','vcenter']" v-for="(item,index) in scope.row.children" :key="item.id">
                            <el-col :span="5">
                                <el-tag  closable @close="removeRightsId(scope.row,item.id)">
                                    {{ item.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                                </el-col>
                            <el-col :span="19">
                                <!-- 循环二级和三级权限 -->
                                <el-row :class="[indexs===0?'':'bdtop','vcenter']" v-for="(items,indexs) in item.children" :key="items.id">
                                    <el-col :span="6">
                                         <el-tag type="success"  closable @close="removeRightsId(scope.row,items.id)">
                                            {{ items.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                         <el-tag type="warning" closable @close="removeRightsId(scope.row,itemss.id)" v-for="itemss in items.children" :key="itemss.id">
                                            {{ itemss.authName }}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>

                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="340px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
               
            </el-table>
        </el-card>   

        <!-- 权限分配弹窗 -->
        <el-dialog
            title="权限分配"
            :visible.sync="setRightDialogVisible"
            @close="setRightsDialogClose"
            width="50%">
            <!-- props声明关系规则 -->
            <el-tree :data="rightTreeList" :props="treeProps" ref="treeRef"
            show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"
            ></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog> 
   </div>
</template>

<script>
export default {
    data(){
        return {
            rolesList:[],
            setRightDialogVisible:false,
            rightTreeList:[],
            treeProps:{
                label:'authName',   //显示字段为authName
                children:'children' //子级字段为children
            },
            defKeys:[105.116],
            roleId:'',
        }
    },
    created(){
        this.getRolesList();
    },
    methods:{
        async getRolesList(){
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status!=200) return this.$message.error("请求角色列表失败")
            this.rolesList = res.data
        },
        async removeRightsId(role,rightId){
            
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)

            if(confirmResult !== 'confirm') return this.$message.info("取消了删除")

            const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status!=200) return this.$message.error("删除失败")
            this.$message.success("删除成功")
            // this.getRolesList()  不能直接从新请求接口，因为页面会重新渲染
            role.children = res.data;   //直接返回单行数据，替换掉就行
        },
        async showSetRightDialog(role){
            this.roleId = role.id;
             const {data:res} = await this.$http.get('rights/tree')
            if(res.meta.status !==200) return this.$message.error("获取权限数据失败")
            this.rightTreeList = res.data
            console.log(res.data)
            // 先递归所有三级节点的ID
            this.getLeafKey(role,this.defKeys);
            console.log(this.defKeys)
            this.setRightDialogVisible = true
        },
        // 通过递归的方式，获取角色的三级ID，并保存到defkeys数组中
        getLeafKey(node,arr){
            //如果没有children证明是最后的节点，直接把id保存到数组
            if(!node.children) return arr.push(node.id)
            //否则遍历children，并再次调用getLeafKey
            node.children.forEach(item=>{
                this.getLeafKey(item,arr)
            })
        },
        setRightsDialogClose(){
            this.defKeys = []
        },
        async allotRights(){
            const keys = [
                //数组使用...是拆分
                ...this.$refs.treeRef.getCheckedKeys(),    //获取所有子项选中数据 返回为arr
                ...this.$refs.treeRef.getHalfCheckedKeys(),  //获取多有半选中数据    返回arrr

            ]

            const idStr = keys.join(",");
            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
            if(res.meta.status !==200) return this.$message.error("分配失败")
            this.$message.success("分配成功")

            this.getRolesList();
            this.setRightDialogVisible = false
        }
    }
}
</script>
<style lang="less" scoped>
    .el-tag{
        margin:7px;
    }

    .bdtop{
        border-top:1px solid #eee;
    }
    .bdbottom{
        border-bottom:1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>